//
//  HomeViewController.swift
//  Sina
//
//  Created by 袁量 on 2016/11/28.
//  Copyright © 2016年 袁量. All rights reserved.
//

import UIKit
import SDWebImage
import MJRefresh
class HomeViewController: BaseTableViewController {
    var tipsLabel : UILabel = UILabel()
    lazy var viewModels : [StatusViewModel] = [StatusViewModel]()
    lazy var titleBtn : TitleButton = TitleButton()
    lazy var popverAnimation : PopoverAnimation = PopoverAnimation {[weak self] (presented) -> () in
        self?.titleBtn.isSelected = presented
    }
//    lazy var photoBrowserAnimator : PhotoBrowserAnimator = PhotoBrowserAnimator()
    override func viewDidLoad() {
        super.viewDidLoad()
        guard isLogIN else {
            visitorView?.setupVisitorInfo(imageName: "visitordiscover_feed_image_house", title: "关注一些人，回这里看看呦什么惊喜")
            visitorView?.startAniamtion()
            return
        }
        setUpHeaderView()
        setUpFooterView()
        setUpTipsLabel()
        setUpNavigationBarItem()
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 200
//        setupNatifications()
        
    }
}

// MARK: - UI 界面
extension HomeViewController {
    func setUpNavigationBarItem() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
        titleBtn.setTitle("袁量", for: .normal)
        titleBtn.addTarget(self, action: #selector(HomeViewController.titleBtnClick(titleBtn:)), for: .touchUpInside)
        navigationItem.titleView = titleBtn
    }
    func setUpHeaderView() {
        let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(HomeViewController.loadNewStatus))
        tableView.mj_header = header
        tableView.mj_header.beginRefreshing()
    }
    func setUpFooterView() {
//        let footer = 
        tableView.mj_footer = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction: #selector(HomeViewController.loadMoreStatus))
    }
    func setUpTipsLabel() {
        navigationController?.navigationBar.insertSubview(tipsLabel, at: 0)
        tipsLabel.backgroundColor = UIColor.orange
//        tipsLabel.alpha = 0.0
        tipsLabel.isHidden = true
        tipsLabel.frame = CGRect(x: 0, y: 10, width: UIScreen.main.bounds.size.width, height: 32)
        tipsLabel.textColor = UIColor.white
        tipsLabel.font = UIFont.systemFont(ofSize: 14)
        tipsLabel.textAlignment = .center
    }
    fileprivate func setupNatifications() {
        NotificationCenter.default.addObserver(self, selector: Selector(("showPhotoBrowser:")), name: NSNotification.Name(rawValue: ShowPhotoBrowserNote), object: nil)
    }

}

// MARK: - 响应事件
extension HomeViewController {
    func titleBtnClick (titleBtn : TitleButton) {
        WWLog(mesage: "点击了标题按钮")
        titleBtn.isSelected = !titleBtn.isSelected
        let popoverVC = PopoverViewController()
        popoverVC.modalPresentationStyle = .custom
        popoverVC.transitioningDelegate = popverAnimation
        popverAnimation.presentViewFrame = CGRect(x: 100, y: 55, width: 180, height: 250)
        present(popoverVC, animated: true, completion: nil)
    }
    /*
    fileprivate func showPhotoBrowser(_ note : Notification) {
        // 0.取出数据
        let indexPath = note.userInfo![ShowPhotoBrowserIndexKey] as! IndexPath
        let picURLs = note.userInfo![ShowPhotoBrowserUrlsKey] as! [URL]
        let object = note.object as! PicCollectionView
        
        // 1.创建控制器
        let photoBrowserVc = PhotoBrowserController(indexPath: indexPath as NSIndexPath, picURLs: picURLs as [NSURL])
        
        // 2.设置modal样式
        photoBrowserVc.modalPresentationStyle = .custom
        
        // 3.设置转场的代理
        photoBrowserVc.transitioningDelegate = photoBrowserAnimator
        
        // 4.设置动画的代理
        photoBrowserAnimator.presentedDelegate = object as? AnimatorPresentedDelegate
//        PhotoBrowserAnimator.indexPath = indexPath
//        PhotoBrowserAnimator.dismissDelegate = photoBrowserVc
        
        // 以modal的形式弹出控制器
        present(photoBrowserVc, animated: true, completion: nil)
    }
 */

    
}

// MARK: - 请求数据
extension HomeViewController {
    func loadNewStatus() {
        WWLog(mesage: "刷新数据")
        loadStatuses(isNewData: true)
    }
    func loadMoreStatus() {
        loadStatuses(isNewData: false)
    }
    func loadStatuses(isNewData : Bool) {
        print("在首页调用加载最新数据")
        var since_id = 0
        var max_id = 0
        if isNewData {
            since_id = viewModels.first?.status?.mid ?? 0
        } else {
            max_id = viewModels.last?.status?.mid ?? 0
        }
        NetworkingTools.shareInstance.loadStatuses(max_id: max_id, since_id: since_id) { (result, error) in
            if error != nil {
                return
            }
            guard let resultArray = result else {
                return
            }
            var tempViewModel = [StatusViewModel]()
            for statusDict in resultArray{
                let status = Status(dict: statusDict)
                let viewModel = StatusViewModel(status: status)
                tempViewModel.append(viewModel)
            }
            if isNewData {
                self.viewModels = tempViewModel + self.viewModels
                self.cacheImages(viewModels: tempViewModel)
            } else {
                self.viewModels = self.viewModels + tempViewModel
                self.cacheImages(viewModels: tempViewModel)
            }
            
            
            
        }
    }
    func cacheImages(viewModels : [StatusViewModel]) {
        let group = DispatchGroup()
        for viewModel in viewModels {
            for picURL in viewModel.picURLs {
                print("要缓存的图片名字\(picURL)")
                group.enter()
                SDWebImageManager.shared().loadImage(with: picURL as URL, options: [], progress: nil, completed: { (_, _, _, _, _, _) in
                    group.leave()
                })
                
                
            }
        }
        group.notify(queue: DispatchQueue.main) { 
            self.tableView.reloadData()
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            self.showTipsLabel(count: viewModels.count)
        }
    }
    func showTipsLabel(count : Int) {
        tipsLabel.isHidden = false
        tipsLabel.text = count == 0 ? "没有新数据呀" : " \(count)条新微博"
        UIView.animate(withDuration: 1.0, animations: { 
            self.tipsLabel.frame.origin.y = 44
//            self.tipsLabel.alpha = 1.0
        }) { (_) in
            UIView.animate(withDuration: 1.0, delay: 1.5, options: [], animations: { 
                self.tipsLabel.frame.origin.y = 10
            }, completion: { (_) in
                self.tipsLabel.isHidden = true
            })
        }
    }
}

// MARK: - tableView 的代理
extension HomeViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModels.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCellID") as! HomeViewCell
        cell.viewModel = viewModels[indexPath.row]
        return cell
    } 
}
